package cn.com.pajx.pajx_visitor_v3.ui.activity;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.rcw.swiperefreshrecyclerview.BaseAdapter;
import com.rcw.swiperefreshrecyclerview.OnItemClickListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.pajx.pajx_visitor_v3.R;
import cn.com.pajx.pajx_visitor_v3.adapter.VisiteHistoryAdapter;
import cn.com.pajx.pajx_visitor_v3.api.Api;
import cn.com.pajx.pajx_visitor_v3.base.BaseRecyclerViewActivity;
import cn.com.pajx.pajx_visitor_v3.bean.EventMessage;
import cn.com.pajx.pajx_visitor_v3.bean.VisiteBean;
import cn.com.pajx.pajx_visitor_v3.bean.VisitePageBean;
import cn.com.pajx.pajx_visitor_v3.ui.fragment.VisitorInfoFragment;
import cn.com.pajx.pajx_visitor_v3.utils.AppConstant;
import cn.com.pajx.pajx_visitor_v3.utils.DateUtil;

/**
 * 历史记录
 */
@SuppressLint("NonConstantResourceId")
public class HistoryActivity extends BaseRecyclerViewActivity<VisiteBean> {

    @BindView(R.id.view_visitor)
    EditText viewVistor;
    @BindView(R.id.view_interviewee)
    EditText viewInterviewee;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.iv_next_day)
    ImageView ivNextDay;

    private final List<VisiteBean> visitorBeans = new ArrayList<>();
    private VisiteHistoryAdapter mAdapter;
    private String selectorDate, currentDate;
    //时间选择器

    private String visitor_name, interviewee_name, order_time;
    private int totalPage;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_history;
    }

    @Override
    protected BaseAdapter<VisiteBean> getAdapter() {
        return mAdapter = new VisiteHistoryAdapter(mContext, R.layout.visite_history_item, visitorBeans);
    }

    @Override
    protected String getApiUrl(boolean isRefresh) {
        if (isRefresh) visitorBeans.clear();
        paramsMap.put("time_plan", order_time);
        paramsMap.put("vis_name", visitor_name);
        paramsMap.put("user_name", interviewee_name);
        return Api.VISITE_HISTORY;
    }

    @Override
    protected void initView() {
        setHeadTitle("拜访历史");
        EventBus.getDefault().register(this);
        //初始化时间
        initCalanderView();
        super.initView();
        initDownTimer();
        initEditListener();
    }

    /**
     * 输入框事件监听
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initEditListener() {
        viewVistor.setOnTouchListener((view, motionEvent) -> {
            resetDownTimer();
            return false;
        });
        viewInterviewee.setOnTouchListener((view, motionEvent) -> {
            resetDownTimer();
            return false;
        });
    }

    @Override
    protected void initRecyclerView() {
        super.initRecyclerView();
        setHelperView(xRecyclerView);
        //条目点击事件监听
        initAdapterListener();
    }

    /**
     * 初始化时间
     */
    private void initCalanderView() {
        currentDate = DateUtil.getCurrentYMD();
        order_time = DateUtil.getCurrentYmd();
        selectorDate = currentDate;
        tvDate.setText(selectorDate);
    }

    /**
     * Adapter条目点击事件监听
     */
    private void initAdapterListener() {
        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void setOnClickListener(View view, int position) {
                cancelDownTimer();
                VisiteBean bean = visitorBeans.get(position);
                VisitorInfoFragment visitorInfoFragment = VisitorInfoFragment.newInstance(bean.getVis_id(), "");
                visitorInfoFragment.show(getSupportFragmentManager(), "visitorInfoFragment");
            }

            @Override
            public void setOnLongClickListener(View view, int position) {

            }
        });
        xRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                resetDownTimer();
            }
        });
    }

    @Override
    protected void showData(String data, String tag) {
        VisitePageBean visitePageBean = new Gson().fromJson(data, VisitePageBean.class);
        if (visitePageBean != null) {
            totalPage = visitePageBean.getPages();
            visitorBeans.addAll(visitePageBean.getRecords() == null ? new ArrayList<>() : visitePageBean.getRecords());
            showEmptyStatus(visitorBeans);
        }
    }

    @Override
    protected int getTotalPage() {
        return totalPage;
    }

    @Override
    protected boolean getLoadMoreEnable() {
        return true;
    }

    @Override
    protected void loadLocalData() {

    }

    @OnClick({R.id.iv_previous_day, R.id.iv_next_day, R.id.tv_search})
    public void onClickViewed(View view) {
        switch (view.getId()) {
            case R.id.iv_previous_day://前一天
                selectorDate = DateUtil.getPreviousDay(selectorDate);
                order_time = selectorDate.replaceAll("-", "");
                tvDate.setText(selectorDate);
                ivNextDay.setBackgroundResource(R.mipmap.arrow_right_white);
                onRefresh();
                break;
            case R.id.iv_next_day://后一天
                if (isCanToNextDay()) {
                    selectorDate = DateUtil.getNextDay(selectorDate);
                    order_time = selectorDate.replaceAll("-", "");
                    tvDate.setText(selectorDate);
                    if (TextUtils.equals(currentDate, selectorDate)) {
                        ivNextDay.setBackgroundResource(R.mipmap.arrow_right_grey);
                    } else {
                        ivNextDay.setBackgroundResource(R.mipmap.arrow_right_white);
                    }
                    onRefresh();
                }
                break;
            case R.id.tv_search://搜索
                hideSoftInput();
                visitor_name = viewVistor.getText().toString().trim();
                interviewee_name = viewInterviewee.getText().toString().trim();
                resetDownTimer();
                onRefresh();
                break;
        }
    }

    private boolean isCanToNextDay() {
        long current_day = Long.parseLong(currentDate.replaceAll("-", ""));
        long selector_day = Long.parseLong(selectorDate.replaceAll("-", ""));
        return selector_day < current_day;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage bean) {
        if (TextUtils.equals(AppConstant.FRAGMENTDIALOG_DISMISS, bean.getMessage())) {
            resetDownTimer();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}